package com.cskaoyan.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @ClassName MarketSessionManager
 * @Description TODO
 * @Author by Lester
 * @Date 2022/11/21 22:00
 * @Version 1.0
 */
@Component
public class MarketSessionManager extends DefaultWebSessionManager {

    private static final String MARKET_ADMIN_TOKEN = "X-CskaoyanMarket-Admin-Token";
    private static final String MARKET_WX_TOKEN = "X-CskaoyanMarket-Token";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        boolean authenticated = false;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        String requestURI = httpServletRequest.getRequestURI();
//        System.out.println("requestURI = " + requestURI);
//        boolean isRegister = "/wx/auth/register".equals(requestURI);
        try {
            Subject subject = SecurityUtils.getSubject();
            authenticated = subject.isAuthenticated();
        } catch (Exception e) {
            //没有权限 ，可能是服务器重启导致的
        }
        // 禁止在url上拼接 JSessionId 防止重定向时url拼接JSessionId导致400错误

        // request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, false);

        /*try {
            authenticated = SecurityUtils.getSubject().isAuthenticated();
        } catch (Exception e) {
        }*/



        String sessionId = httpServletRequest.getHeader(MARKET_ADMIN_TOKEN);
        if (sessionId != null & !"".equals(sessionId)) {
            if (!authenticated) {
                request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, false);
            }
            return sessionId;
        }
        String sessionId2 = httpServletRequest.getHeader(MARKET_WX_TOKEN);
        if (sessionId2 != null & !"".equals(sessionId2)) {
            if (!authenticated) {
                request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, false);
            }
            return sessionId2;
        }
        return super.getSessionId(request, response);
    }
}
